var ObserverMgr = require("ObserverMgr");
var Byte = require("Byte");
var DataEnCode = require("DataEnCode");
var DataDeCode = require('DataDeCode');

module.exports = {
    ws: null,

    init: function () {
        this.ws = null;
        var serverIP = "122.114.150.35";
        serverIP = "192.168.1.165";
        serverIP="127.0.0.1";
        var url = "ws://" + serverIP + ":8010/g";
        this.ws = new WebSocket(url);
        this.ws.binaryType = 'arraybuffer';
        this.ws.onopen = this.onOpen.bind(this);
        this.ws.onmessage = this.onMessage.bind(this);
        this.ws.onerror = this.onError.bind(this);
        this.ws.onclose = this.onClose.bind(this);
    },
    //////////////////////Socket 重连/////////////////////////////////////
    reConnect(){
        this.init();
    },
    //////////////////////Socket 打开/////////////////////////////////////
    onOpen: function () {
        console.log("[Socket Open]");
        ObserverMgr.dispatchMsg(GameGlobalMsg.Socket.Open, null);
    },

    //////////////////////////Socket 错误/////////////////////////////////
    onError: function () {
        console.log("[Socket Error]");
        this.ws = null;
        ObserverMgr.dispatchMsg(GameGlobalMsg.Socket.Error, null);
    },
    //////////////////////////Socket关闭//////////////////////////////////
    onClose: function () {
        this.ws = null;
        console.log("[Socket Close]");
    },
    disConnect(){
        if (this.ws && this.ws.readyState == WebSocket.OPEN) {
            ObserverMgr.dispatchMsg(GameLocalMsg.Net.OnNetDisconnect, null);
            this.ws.close();
            this.ws = null;
        }
    },
    send: function (msgObject, data = {}) {
        if (this.ws) {
            if (this.ws.readyState == WebSocket.OPEN) {
                var type = msgObject['type'] + 4;
                var id = msgObject['id'] + 4;
                var msg = msgObject["msg"];
                this._showSendData(type, id, msg, data);

                var byte = new DataEnCode();
                byte.writeInt(type);
                byte.writeInt(id);
                msgObject.encode(byte, data);
                // 打印二进制数据
                console.log(msg + "=> len:" + byte.getBinaryLen() + "   [" + byte.getBinaryString() + "]");
                this.ws.send(byte.getBuffer());
                ObserverMgr.dispatchMsg(GameGlobalMsg.Socket.Send, msgObject['msg']);
                return true;
            } else {
                console.log("网络失去连接...");
                this.onClose();
                return false;
            }
        } else {
            console.log("网络连接出现问题:可能没有初始化网络,或网络失去连接!");
            this.onClose();
            return false;
        }
    },

    _showSendData(type, id, msg, data){
        var sendData = {type: type, id: id, msg: msg, data: data};
        var str = JSON.stringify(sendData);
        console.log("[Socket 发送数据==>]" + str);
    },

    onMessage: function (event) {
        ObserverMgr.dispatchMsg(GameGlobalMsg.Socket.Recv, null);

        var receiveData = event.data;
        var byte = new DataDeCode(receiveData);
        var type = byte.readInt();
        var id = byte.readInt();
        var msgObject = MJNetMsg.getReceiveHandlerByTypeAndID(type, id);
        if (msgObject) {
            var msg = msgObject['msg'];
            var decodeData = msgObject.decode(byte);
            this._showRectData(type, id, msg, decodeData);
            ObserverMgr.dispatchMsg(msg, decodeData);
        } else {
            //ObserverMgr.dispatchMsg(GameErrorMsg.ErrorString, [msg, code, data]);
        }
    },

    _showRectData(type, id, msg, data){
        var str = JSON.stringify({type: type, id: id, msg: msg, data: data});
        console.log("[Socket 接收数据<==]" + str);
    }
}